﻿using CommonServiceLocator;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Zhy.DigitaPlatform.IDataAccess;
using Zhy.DigitaPlatform.Models;

namespace Zhy.DigitaPlatform.ViewModels
{
    /// <summary>
    /// 登陆业务类
    /// </summary>
    public class LoginViewModel : ViewModelBase
    {
        /// <summary>
        /// 用户信息-用于登陆
        /// </summary>
        public UserModel User { get; set; }
        /// <summary>
        /// 登陆按钮
        /// </summary>
        public RelayCommand<object> LoginCommand { get; set; }

        public string _failedMsg;
        public string FailedMsg
        {
            get { return _failedMsg; }
            set { Set(ref _failedMsg, value); }
        }

        /// <summary>
        /// 容器注册的数据库操作类
        /// </summary>
        ILocalDataAccess _localDataAccess;

        /// <summary>
        /// 初始化
        /// </summary>
        public LoginViewModel(ILocalDataAccess localDataAccess)
        {
            _localDataAccess = localDataAccess;
            if (!IsInDesignMode)
            {
                User = new UserModel();
                LoginCommand = new RelayCommand<object>(DoLogin);
            }
        }

        /// <summary>
        /// 登陆方法
        /// </summary>
        /// <param name="obj"></param>
        private void DoLogin(object obj)
        {
            // 对接数据库
            try
            {
                var data = _localDataAccess.Login(User.UserName, User.Password);
                if (data == null) throw new Exception("登录失败，没有用户信息");

                // 记录一下主窗口所需要的用户信息，对于SimpleIOC   同一个实例，默认是单例
                var main = ServiceLocator.Current.GetInstance<MainViewModel>();
                if (main != null)
                { // 赋值用户信息
                    main.GlobalUserInfo.UserName = User.UserName;
                    main.GlobalUserInfo.Password = User.Password;
                    main.GlobalUserInfo.RealName = data.Rows[0]["real_name"].ToString()!;
                    main.GlobalUserInfo.UserType = int.Parse(data.Rows[0]["user_type"].ToString()!);
                    main.GlobalUserInfo.Gender = int.Parse(data.Rows[0]["gender"].ToString()!);
                    main.GlobalUserInfo.Department = data.Rows[0]["department"].ToString()!;
                    main.GlobalUserInfo.PhoneNumber = data.Rows[0]["phone_num"].ToString()!;
                }
                // 关闭登陆页面
                (obj as Window).DialogResult = true;
            }
            catch (Exception ex)
            {
                FailedMsg = ex.Message;
            }
        }
    }
}
